<template>
  <!-- :class="{'no-touch': isExam}"  添加这个样式会导致 富文本插件异常 -->
  <div style="padding: 0 10%" class="flex" v-loading="formLoading">
    <el-card class="qs-title">
      <h3 style="font-weight: normal; margin: 10px 0">{{ qbName }}</h3>

      <div class="p-b-10 flex justify-between" v-show="isExam">
        <span>总分：100</span>
        <span>时长：120分钟</span>
      </div>

      <div class="divider" />

      <!-- <span :key="item.order" v-for="item in answer">
        <el-tag :type="item.order == curIdx ? 'primary' : (item.completed ? 'success' : 'info')" @click="curIdx = item.order;" :effect="item.order == curIdx ? 'dark' : 'light'"  class="qs-title-tag">{{ item.order }}</el-tag>
      </span>-->

      <!-- <div v-for="k in Object.keys(subject)" :key="k">
        <div v-if="subject[k].subs.length">
          <div style="font-size: 14px;" class="mt10">{{ k +'.'+ subject[k].label }}</div>
          <span :key="item.order" v-for="item in subject[k].subs">
            <el-tag :type="item.order == curIdx ? 'primary' : (item.completed ? 'success' : 'info')" @click="curIdx = item.order;" :effect="item.order == curIdx ? 'dark' : 'light'"  class="qs-title-tag">{{ item.order }}</el-tag>
          </span>
        </div>
      </div>-->
      <!-- v-for="(value, key, index) in myObject" 遍历的顺序会基于对该对象调用 Object.keys() 的返回值来决定。 -->
      <div v-for="(value, QuType, i) in subject" :key="i">
        <div v-if="value.subs.length">
          <div style="font-size: 14px;" class="mt10">{{ QuType +'.'+ value.label }}</div>
          <span v-for="item in value.subs" :key="item.order">
            <el-tag
              :type="tagStyle(item).type"
              :effect="tagStyle(item).effect"
              class="qs-title-tag"
              @click="curIdx = item.order;"
            >{{ item.order }}</el-tag>
          </span>
        </div>
      </div>

      <div class="align-center p-y-20" v-show="isExam">
        <el-button type="primary" size="medium" @click="submitCheck">提交试卷</el-button>
      </div>
    </el-card>

    <el-card class="qs-container">
      <div class="qs-last-time border-bottom" v-show="isExam">
        <span>剩余时间</span>
        <div class="m-t-5 font-18 text-danger">{{ formatSeconds(remainTime) }}</div>
      </div>

      <el-empty v-if="!(currentQu.hasOwnProperty('objId') || currentQu.hasOwnProperty('subId'))" />

      <question
        v-else
        ref="qus"
        isMultUse
        :subject="subject"
        :curIdx="curIdx"
        :currentQu="currentQu"
        :answer="answer"
        :isExam="isExam"
        @change="quChanges"
      />

      <el-collapse v-model="activeAnswer" class="m-t-20" v-show="showAnswer">
        <el-collapse-item :name="1">
          <div slot="title" style="color: #409EFF;">解析</div>
          <div class="flex items-center">
            <span>我的答案：</span>
            <!-- :style="{color: isCurrect?'green':'red'}" -->
            <div>
              <span style="margin-right: 40px;">{{ uanswer }}</span>
              <!-- <i v-show="answer[curIdx-1].quAnswer" :class="isCurrect?'el-icon-check':'el-icon-close'"  style="font-size: 18px;" /> -->
            </div>
          </div>
          <div style="width: 90%;">正确答案：{{ quAnswer }}</div>
          <div class="flex">
            <div
              style="width: 90%;"
            >答案解析：{{ currentQu.objAnswerContent ? currentQu.objAnswerContent : currentQu.subAnswerContent }}</div>
            <Enclosure :currentQu="currentQu" isAnswer />
          </div>
        </el-collapse-item>
      </el-collapse>

      <div class="operaBtn flex justify-between m-t-20">
        <el-button
          type="primary"
          plain
          size="small"
          round
          :disabled="prevDisable"
          @click="curIdx--;"
        >上一题</el-button>
        <el-button type="primary" size="small" round :disabled="nextDisable" @click="curIdx++;">下一题</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getQuAnswer, getUAnswer } from "@/views/Question/child/qu_const";
import { getQuList, getQuDetail, uploadUserQuAnswer } from "@/api/question";
import { getDictByType } from "@/api/common";
import { formatSeconds } from "@/utils";

export default {
  components: {
    question: () => import("@/views/Question/comp/question.vue"),
    Enclosure: () => import("@/views/Question/comp/enclosure.vue")
  },
  props: {
    isExam: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      quType: {}, // 题目类型
      qbId: null, // 题库id
      qbName: null, // 题库名称
      formLoading: false,
      quList: [], // 包含题目id类型的列表
      answer: [], // 用户作答
      params: {
        quId: null,
        quType: null,
        qbPattern: null
      },
      quObjList: [], // 题目详情列表
      curIdx: 1, // 题目序号
      currentQu: {}, // 当前显示的题目
      subject: {}, // 左侧题号列表
      examTime: 120, // 分钟
      remainTime: 0, // 剩余时间秒
      timer: null,
      activeAnswer: null
    };
  },
  computed: {
    showAnswer() {
      // 显示解析，不是考试  && (背题模式 || (答题模 && 答了题))
      return (
        !this.isExam &&
        (!this.isAnswer ||
          (this.answer[this.curIdx - 1]
            ? this.answer[this.curIdx - 1].completed
            : false && this.isAnswer))
      );
    },
    uanswer() {
      // const type = this.answer[this.curIdx-1] ? this.answer[this.curIdx-1].quType : ""
      // const answer = this.answer[this.curIdx-1] ? this.answer[this.curIdx-1].uanswer : ""
      // const answers = this.answer[this.curIdx-1] ? this.answer[this.curIdx-1].uanswers : []
      // 简化
      const {
        quType: type = "",
        quAnswer: answer = "",
        uanswers: answers = []
      } = this.answer[this.curIdx - 1] || {};
      return getUAnswer(type, answer, answers);
    },
    quAnswer() {
      const question = this.currentQu;
      const has = Object.prototype.hasOwnProperty;

      const type = has.call(question, "objType")
        ? question.objType
        : question.subType;
      const answer = has.call(question, "objAnswer")
        ? question.objAnswer
        : question.subAnswer;
      return getQuAnswer(type, answer);
    },
    // isCurrect() {
    //   return this.answer[this.curIdx-1].quAnswer == this.currentQu.objAnswer
    // },
    isAnswer() {
      // 背题模式0 or 答题模式1
      return this.params.qbPattern == 1;
    },

    prevDisable() {
      return this.curIdx == 1 ? true : false;
    },
    nextDisable() {
      return this.curIdx == this.quList.length ? true : false;
    },
    undone() {
      // let count = 0
      // this.answer.forEach(x => {
      //   if(!x.completed) count ++
      // })
      // return count
      // 简化
      return this.answer.reduce(
        (pre, cur) => (cur.completed ? pre : (pre += 1)),
        0
      );
    }
  },
  watch: {
    curIdx: {
      handler: "getQu"
      // immediate: true,
    }
  },
  async created() {
    await this.init();
    await this.getQuList();
    this.setActiveAnswer();
  },
  beforeDestroy() {
    window.clearInterval(this.timer);
  },
  methods: {
    quChanges(qu) {
      // 答题模式上传题目作答信息
      if (this.isAnswer) {
        if (qu.quAnswer)
          // 答案不为空上传
          uploadUserQuAnswer(qu);
      }
    },
    // 设置高亮
    setActiveAnswer() {
      this.activeAnswer = this.isAnswer ? 0 : 1;
    },
    // 题目选择标签高亮
    tagStyle(item) {
      const effect = item.order == this.curIdx ? "dark" : "light";
      const type =
        item.order == this.curIdx
          ? "primary"
          : item.completed
          ? "success"
          : "info";
      return { type, effect };
    },
    // 初始化
    async init() {
      const r = await getDictByType("qb_qu_type");
      r.data.forEach(x => {
        this.quType[x.dictValue] = x.dictLabel;
        this.subject[x.dictValue] = {
          label: x.dictLabel,
          subs: []
        };
      });
      this.qbId = this.$route.query.qbId;
      const qbObj =
        window.sessionStorage.getItem("qbObj") &&
        JSON.parse(window.sessionStorage.getItem("qbObj"));
      if (qbObj) {
        this.qbName = qbObj.qbName;
        this.params.qbPattern = qbObj.qbPattern;
      }
    },
    // 格式化时间
    formatSeconds(theTime) {
      return formatSeconds(theTime);
    },
    // 定时器
    timeReduce() {
      this.timer = setInterval(() => {
        if (this.remainTime <= 0) {
          this.submitForm();
        } else {
          // ++this.answer.doTime
          --this.remainTime;
        }
      }, 1000);
    },
    // 获取题目列表
    async getQuList() {
      this.formLoading = true;
      const r = await getQuList(this.qbId);
      if (r.code == 200) {
        this.quList = r.data;
        this.initQuList();
        this.getQu();
      }
      if (this.isExam) {
        this.remainTime = this.examTime * 60;
        this.timeReduce();
      }
      this.formLoading = false;
      // console.log(this.subject)
    },
    // 初始化题目列表
    initQuList() {
      this.quList.forEach((item, idx) => {
        this.subject[item.quType].subs.push({
          order: idx + 1,
          quId: item.quId,
          completed: false
        });
        this.answer.push({
          order: idx + 1,
          qbId: this.qbId,
          quId: item.quId,
          quType: item.quType,
          completed: false,
          quAnswer: "",
          uanswers: [],
          subanswer: ""
        });
      });
    },
    // 获取题目信息
    async getQu() {
      this.setActiveAnswer();
      this.params.quId = this.quList[this.curIdx - 1].quId;
      this.params.quType = this.quList[this.curIdx - 1].quType;
      let idx = this.getQuInx();
      if (idx != -1) {
        return (this.currentQu = this.quObjList[idx]);
      }
      const res = await getQuDetail(this.params).catch(
        () => (this.currentQu = {})
      );
      if (res.code == 200) {
        this.currentQu = res.data;
        this.quObjList.push(res.data);
        // 背题模式设置答案
        if (!this.isAnswer) this.setAnswer(res.data);
      }
    },
    // 设置答案回显
    setAnswer(question) {
      const has = Object.prototype.hasOwnProperty;
      if (has.call(question, "objAnswer")) {
        // 客观题
        if (question.objType == 3) {
          // 多选题
          this.answer[this.curIdx - 1].uanswers = question.objAnswer.split("$");
        } else {
          // 单选、判断
          this.answer[this.curIdx - 1].quAnswer = question.objAnswer;
        }
      } else {
        // 主观题
        if (question.subType == 5) {
          // 简答题
          this.answer[this.curIdx - 1].subanswer = question.subAnswer;
        }
        this.answer[this.curIdx - 1].quAnswer = question.subAnswer;
      }
    },
    getQuInx() {
      return this.quObjList.findIndex(x => x.objId == this.params.quId);
    },
    // 提交前检查
    async submitCheck() {
      if (this.undone != 0) {
        try {
          await this.$confirm(
            `还有 ${this.undone} 道题目未做答, 是否交卷?`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
          );
          this.submitForm();
        } catch (e) {
          console.log(e);
        }
      } else {
        this.submitForm();
      }
    },
    // 提交
    async submitForm() {
      window.clearInterval(this.timer);
      console.log("submit", this.undone, this.answer);
      this.$alert("试卷提交成功", "提示", {
        confirmButtonText: "确定",
        callback: () => {
          this.$router.replace("/question");
        }
      });
    }
  }
};
</script>

<style scoped>
@import url("./topic.css");
</style>
